import { defineStore } from "pinia";
import { ref } from "vue";

export const useCartStore = defineStore("CartStore", () => {
  const cartList = ref([]);
  const isDelete = ref(true);
  const edit = ref(true);
  const orderList = ref([]);
  const userAddress = ref([
    {
      id: 1001,
      name: "jason",
      tel: "15874857777",
      province: "广东省",
      city: "深圳市",
      county: "南山区",
      addressDetail: "深圳湾",
      isDefault: true,
      areaCode: "110101",
    },
    {
      id: 1002,
      name: "allen",
      tel: "15874859685",
      province: "湖北省",
      city: "武汉市",
      county: "武昌区",
      addressDetail: "黄鹤楼",
      isDefault: false,
      areaCode: "110101",
    },
  ]);
  const AppendorderList = ref([]);
  const DoAppendorderList = () => {
    AppendorderList.value = AppendorderList.value.concat(orderList.value);
  };
  const addCart = (value) => {
    cartList.value = value;
  };
  const changeDelete = () => {
    isDelete.value = !isDelete.value;
  };
  const deleteCart = (value) => {
    cartList.value = value;
  };
  const changeEdit = (value) => {
    if (value) {
      edit.value = true;
    } else {
      edit.value = !edit.value;
    }
  };
  const pay = (value) => {
    orderList.value = value;
  };
  const Addaddress = (value) => {
    userAddress.value.map((item) => {
      if (value.isDefault) {
        item.isDefault = false;
      }
    });
    userAddress.value.push(value);
  };
  const editAddress = (value) => {
    userAddress.value = userAddress.value.map((item) => {
      if (value.isDefault) {
        item.isDefault = false;
      }
      if (item.id === value.id) {
        return value;
      } else {
        return item;
      }
    });
  };
  const deleteAddress = (value) => {
    userAddress.value = userAddress.value.filter((item) => {
      return !(item.id === value.id);
    });
    if (value.isDefaul) {
      userAddress.value[0].isDefault = true;
    }
  };
  return {
    isDelete,
    cartList,
    edit,
    orderList,
    userAddress,
    AppendorderList,
    addCart,
    changeDelete,
    deleteCart,
    changeEdit,
    pay,
    DoAppendorderList,
    Addaddress,
    editAddress,
    deleteAddress,
  };
});
